<?php
/**
 * 优惠券逻辑层
 * @author lee
 */
namespace app\common\logic;
use app\common\model\CouponGenerate;
use app\facade\UserLogs;

class Coupon extends Base
{
    /**
     * 重组提交信息
     * @param  array $data 请求的信息
     */
    public function recombine($data)
    {
        if (empty($data['coupon_name'])){
            exception("请填写优惠减名称");
        }
        if (empty($data['description'])){
            exception("请填写优惠减描述");
        }
        if (empty($data['class_id'])){
            exception("请选择优惠劵类别");
        }
        if ($data['coupon_type'] != 0 && $data['coupon_type'] != 1 ){
            exception("请选择优惠劵类型");
        }
        if (empty($data['limit_price'])){
            exception("请填写限制使用金额");
        }
        if (empty($data['offset_price'])){
            exception("请填写冲抵金额");
        }
        if (empty($data['number'])){
            exception("请填写优惠券数量");
        }
        if (empty($data['pbegin'])){
            exception("请选择有效期开始时间");
        }
        if (empty($data['pend'])){
            exception("请选择有效期结束时间");
        }
        if (empty($data['id'])){
            $data['surplus_number'] = $data['number'];
        }
        $data['pbegin'] = strtotime($data['pbegin']);
        $data['pend'] = strtotime($data['pend']) + (60*60*24-1);
        return $data;
    }
    public function save($data)
    {
        $id =  parent::save($data); // TODO: Change the autogenerated stub
        if (is_numeric($id)){
            for ($i=1;$i<=$data['number'];$i++){
                CouponGenerate::create([
                    'coupon_id' => $id,
                    'verification_code' => $this->generateVerificationCode()
                ]);
            }
        }
        return $id;
    }
    /**
     * 删除
     * @param  array $data 请求的信息
     */
    public function delete($data)
    {
        // 验证器验证
        $validateResult = validate_rule($data, 'del');
        if ($validateResult !== true) exception($validateResult);
        if (!isset($data['id']) || !$data['id']) {
            exception('请选择要删除的信息');
        }
//        $release_coupon = CouponGenerate::where("coupon_id",$data['id'])->where("is_release",1)->field('id')->find();
//        if (!empty($release_coupon)){
//            exception('当前优惠劵已发布，不可删除');
//        }
        $model = $this->getModel();
        $obj   = new $model;
        if (property_exists($obj, 'softId') && $obj->softId) {
            $model::destroy($data['id']);
        } else {
            $model::destroy($data['id'], true);
        }
        CouponGenerate::where("coupon_id",$data['id'])->delete();
        $id = is_array($data['id']) ? implode(',', $data['id']) : $data['id'];
        UserLogs::insertLog(['title' => '删除'.$obj->tableName, 'content' => "id=".$id]);
        return true;
    }
    public function generateVerificationCode(){
        return time().mt_rand(10000,99999);
    }
}
